package com.hu.jie.day01.fragment;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.hu.jie.day01.R;
import com.hu.jie.day01.bean.LiWuShuoBean;
import com.hu.jie.day01.utils.OKHttpUtils;

import java.io.IOException;

/**
 * A simple {@link Fragment} subclass.
 */
public class LeftFragment extends Fragment {
    private Activity mActivity;
    private String mUrl;
    private WebView webView;

    public LeftFragment() {
    }


    public static LeftFragment newIntance(String url){
        LeftFragment fragment = new LeftFragment();
        Bundle bundle = new Bundle();
        bundle.putString("url",url);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        mActivity = getActivity();
        super.onCreate(savedInstanceState);
        if (getArguments()!=null){
            mUrl = getArguments().getString("url");
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_left, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        webView = (WebView) view.findViewById(R.id.webview);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        WebSettings settings = webView.getSettings();
        settings.setBuiltInZoomControls(true);
        settings.setJavaScriptEnabled(true);
        settings.setDisplayZoomControls(true);
        OKHttpUtils.newInstance(mActivity).getAsyncMainData(mUrl, new OKHttpUtils.MyCallBack() {
            @Override
            public void onFailure(IOException e) {

            }

            @Override
            public void onResponse(String result) {
                final LiWuShuoBean bean = new Gson().fromJson(result,LiWuShuoBean.class);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadDataWithBaseURL(null,bean.getData().getDetail_html(), "text/html",  "utf-8", null);
                    }
                });
            }
        });
    }
    Handler mHandler = new Handler();
}
